<template>
  <!-- 发货信息，用于导出代发货订单的excel交给快递公司 -->
  <el-dialog
    v-model="visible"
    :modal="false"
    :title="$t('order.uploadTips1')"
    :close-on-click-modal="false"
    :class="['box', $t('language') === 'English' ? 'box-en' : '']"
    class="components-order-upload"
  >
    <div class="tips">
      <p>
        {{ $t('order.uploadTips0') }}
      </p>
      <p style="margin-top: 10px">
        {{ $t('order.attention') }}:
      </p>
      <p style="margin-top: 10px">
        {{ $t('order.uploadTips2') }}
      </p>
      <p style="margin-top: 10px">
        {{ $t('order.uploadTips3') }}
      </p>
    </div>
    <el-upload
      ref="uploadRef"
      :auto-upload="false"
      :v-loading="loading"
      :before-upload="onBeforeAvatarUpload"
      :file-list="files"
      :limit="1"
      :on-error="onUploadFalse"
      :on-preview="onHandlePreview"
      :on-success="onUploadSuccess"
      :action="http.adornUrl('/order/order/exportOrderExcel')"
      :headers="{ Authorization: cookie.get('b2cAuthorization'), locale: lang }"
      class="upload-demo"
      name="orderExcelFile"
    >
      <template #tip>
        <div class="el-upload__tip" />
      </template>
      <div
        class="default-btn"
        @click="onSubmit"
      >
        {{ $t('order.ImportingFiles') }}
      </div>
      <div
        class="default-btn"
        @click="onExportOrder"
      >
        {{ $t('order.exportOrder') }}
      </div>
      <template #trigger>
        <div class="default-btn primary-btn select">
          {{ $t('order.SelectFile') }}
        </div>
      </template>
    </el-upload>
  </el-dialog>
</template>
<script setup>
import { ElMessage, ElMessageBox } from 'element-plus'
import http from '@/utils/http.js'
import cookie from 'vue-cookies'

const emit = defineEmits(['refreshDataList1', 'refreshDataList1'])
const props = defineProps({
  param: {
    type: Object,
    default: () => {
      return {}
    }
  }
})
const lang = localStorage.getItem('b2cLang') || 'zh_CN'

const onExportOrder = () => {
  if (!props.param.startTime || !props.param.endTime) {
    ElMessage.error($t('order.pleExpOrderFirst'))
    return
  }
  ElMessageBox.confirm($t('order.sureToExport'), $t('text.tips'), {
    confirmButtonText: $t('order.confirm'),
    cancelButtonText: $t('order.cancel'),
    type: 'warning'
  }).then(() => {
    http({
      url: http.adornUrl('/order/order/unDeliveryOrderExcel'),
      methods: 'get',
      params: http.adornParams({
        startTime: props.param.startTime, // 开始时间
        endTime: props.param.endTime // 结束时间
      }),
      responseType: 'blob' // 解决文件下载乱码问题
    }).then(({ data }) => {
      const blob = new Blob([data], {
        type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8'
      })
      const fileName = '待发货订单信息.xlsx'
      const elink = document.createElement('a')
      if ('download' in elink) {
        // 非IE下载
        elink.download = fileName
        elink.style.display = 'none'
        elink.href = URL.createObjectURL(blob)
        document.body.appendChild(elink)
        elink.click()
        URL.revokeObjectURL(elink.href) // 释放URL 对象
        document.body.removeChild(elink)
      } else {
        // IE10+下载
        navigator.msSaveBlob(blob, fileName)
      }
    }).catch(e => {
      ElMessage.error(e)
    })
  })
}
const visible = ref(false)
const loading = ref(false)
const files = ref([])
const onUploadSuccess = response => {
  alert(response.data || $t('order.fileSuccess'))
  loading.value = false
  files.value = []
  visible.value = false
  emit('refreshDataList1')
}
const onUploadFalse = () => {
  loading.value = false
  alert($t('order.fileUploadFail'))
}
const init = () => {
  visible.value = true
  loading.value = false
  files.value = []
}
// 上传前对文件的大小的判断
let upload = false

const onBeforeAvatarUpload = file => {
  upload = true
  const extension = file.name.split('.')[1] === 'xls'
  const extension2 = file.name.split('.')[1] === 'xlsx'
  const isLt2M = file.size / 1024 / 1024 < 10
  if (!extension && !extension2) {
    alert($t('order.downloadTemplateTips1'))
    return false
  }
  if (!isLt2M) {
    alert($t('order.downloadTemplateTips2'))
    return false
  }
  loading.value = true
  return extension || (extension2 && isLt2M)
}
const uploadRef = ref(null)

const onSubmit = () => {
  upload = false
  uploadRef.value?.submit()
  if (!upload) {
    ElMessage.error($t('order.uploadFile'))
  }
}
const onHandlePreview = file => {
  if (file.response.status) {
    alert($t('order.fileSuccess'))
  } else {
    alert($t('order.fileFail'))
  }
  visible.value = false
  emit('refreshDataList1')
}
defineExpose({ init })
</script>
<style scoped lang="scss">
.components-order-upload {
  div :deep(.el-dialog__body) {
    padding: 20px;
  }
  .tips {
    margin-bottom: 30px;
  }
  .select {
    margin-right: 10px;
  }
  .box :deep(.el-dialog) {
    width: 40%;
  }

  @media (max-width: 1660px) {
    .box-en :deep(.el-dialog) {
      width: 69% !important;
    }
  }
}
</style>
